﻿using System;
using System.ComponentModel;
using System.Windows;

using TrueCode.Core.Aspects;

namespace EMan.GUI.Common.EntityEditing
{
  /// <summary>
  /// Interaction logic for EntityEditorWindow.xaml
  /// </summary>
  public partial class EntityEditorViewHost : Window
  {
    private readonly IEntityEditorGuiElement _guiElement;
    readonly FrameworkElement _control;

    private bool _isForceClosing;
    private bool _isClosing;
    private bool _cancelClosing;

    public EntityEditorViewHost( [NotNull] IEntityEditorGuiElement guiElement )
    {
      if( guiElement == null ) throw new ArgumentNullException( "guiElement" );

      _guiElement = guiElement;
      InitializeComponent();

      _control = guiElement.Control;

      guiElement.Closed += OnGuiElement_Closed;

      Content = _control;
    }

    #region Overrides of Window
    protected override void OnContentRendered( EventArgs e )
    {
      MinWidth = ActualWidth;
      MinHeight = ActualHeight;

      if( !double.IsInfinity( _control.MaxWidth ) )
        MaxWidth = ActualWidth;

      if( !double.IsInfinity( _control.MaxHeight ) )
        MaxHeight = ActualHeight;
    }
    #endregion

    void OnGuiElement_Closed(object sender, EventArgs e)
    {
      if( _isClosing )
        _cancelClosing = false;
      else
      {
        _isForceClosing = true;
        Close();
      }
    }

    #region Overrides of Window
    protected override void OnClosing( CancelEventArgs e )
    {
      if( _isForceClosing )
        e.Cancel = false;
      else
      {
        _cancelClosing = true;
        _isClosing = true;

        _guiElement.AskToClose();

        e.Cancel = _cancelClosing;

        if( _cancelClosing )
          _isClosing = false;
      }
    }
    #endregion

  }
}
